package com.tenton.commons;

import com.alibaba.fastjson.JSON;
import com.tenton.dao.StudentDao;
import com.tenton.exception.AgeFormatException;
import com.tenton.exception.DataNullPointerException;
import com.tenton.pojo.Student;
import com.tenton.utils.ConstantUtil;
import com.tenton.utils.MessageConstantUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpSession;
import java.sql.Timestamp;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * @Date: 2021/2/7
 * @Author: Tenton
 * @Description: 提取公共部分
 */
@Component
public class OperateCommon {
    @Autowired
    private StudentDao studentDao;
    @Autowired
    private RedisTemplate<String,String> redisTemplate;
    public  Map<String,String> addStudentCommons(String name, String idCard, String ageStr, String address, Timestamp timestamp, HttpSession session) throws AgeFormatException, DataNullPointerException {
        Map<String,String> map = new HashMap();
        //获取session域中的管理员Id
        int adminId = (int) session.getAttribute("adminId");
        boolean compareAll = compareAll(name, idCard, ageStr, address);
        //姓名、身份证号码、年龄、地址都不为空
        if (compareAll) {
            //判断年龄格式是否正确
            if (ageStr.matches(ConstantUtil.AGEREG) && idCard.matches(ConstantUtil.IDCARDREG)) {
                //根据学生身份证号码查询学生（身份证号码唯一）
                Student stuIdCard = studentDao.findByIdCard(idCard);
                //将年龄转为整形
                int age = Integer.parseInt(ageStr);
                //表示此学生数据未存在,添加学生数据
                if (stuIdCard == null) {
                    Student student = new Student(name, idCard, age, address, ConstantUtil.UNSTUDENTSTATUS);
                    //设置创建人Id
                    student.setCreateId(adminId);
                    //设置创建时间
                    student.setCreateTime(timestamp);
                    studentDao.save(student);
                    //此时再次查询，是因为学生已生成学号
                    Student byIdCard = studentDao.findByIdCard(idCard);
                    //将学生对象转换为JSON字符串,存入redis中
                    String s = JSON.toJSONString(byIdCard);
                    redisTemplate.boundSetOps("studentInfo").add(s);
                    map.put("code", MessageConstantUtil.ADD_STUDENT_SUCCESS);
                    //此学生数据存在
                } else {
                    //更改学生信息，保存数据库
                    stuIdCard.setName(name);
                    stuIdCard.setIdCard(idCard);
                    stuIdCard.setAge(age);
                    stuIdCard.setAddress(address);
                    stuIdCard.setUpdateId(adminId);
                    stuIdCard.setUpdateTime(timestamp);
                    stuIdCard.setStudentStatus(ConstantUtil.UNSTUDENTSTATUS);
                    //获取redis中所有数据
                    Set<String> studentInfo = redisTemplate.boundSetOps("studentInfo").members();
                    //遍历
                    for (String stu : studentInfo) {
                        //将JSON数据转换为对象
                        Student student = JSON.parseObject(stu, Student.class);
                        boolean compareStudents = compareStudents(stuIdCard, student);
                        //判断数据是否一致，不一致就修改
                        if (compareStudents){
                            //将信息一致的学生信息进行JSON字符串转换操作
                            String stu1 = JSON.toJSONString(student);
                            //redis删除对应数据
                            redisTemplate.boundSetOps("studentInfo").remove(stu1);
                            //更改学生姓名
                            student.setName(name);
                            //更改学生身份证号码
                            student.setIdCard(idCard);
                            //更改年龄
                            student.setAge(age);
                            //更改地址
                            student.setAddress(address);
                            //设置修改人Id
                            student.setUpdateId(adminId);
                            //设置修改时间
                            student.setUpdateTime(timestamp);
                            //将状态更改为未操作状态
                            student.setStudentStatus(ConstantUtil.UNSTUDENTSTATUS);
                            //将学生对象转换为JSON字符串,存入redis中
                            String newStu = JSON.toJSONString(student);
                            redisTemplate.boundSetOps("studentInfo").add(newStu);
                        }
                    }
                    studentDao.save(stuIdCard);
                    map.put("code", MessageConstantUtil.UPDATE_STUDENT_SUCCESS);
                }
            }else {
                map.put("code",MessageConstantUtil.NUM_FORMAT_FAIT);
                throw new AgeFormatException("表中学生年龄或身份证数据格式不正确！");
            }
        }else {
            map.put("code",MessageConstantUtil.DATA_NULL_POINT);
            throw new DataNullPointerException("表中学生数据存在空值！");
        }
        return map;
    }

    /**
     * 对从前端获取的值进行非空验证
     * @param name
     * @param idCard
     * @param ageStr
     * @param address
     * @return
     */
    public boolean compareAll(String name, String idCard, String ageStr, String address){
        boolean nameFlag = true;
        boolean idCardFlag = true;
        boolean ageFlag = true;
        boolean addressFlag = true;
        //判断姓名是否为空
        if (name == "" || name == null){
            nameFlag = false;
        }
        //判断身份证号码是否为空
        if (idCard == "" || idCard == null){
            idCardFlag = false;
        }
        //判断年龄是否为空
        if (ageStr == "" || ageStr == null){
            ageFlag = false;
        }
        //判断地址是否为空
        if (address == "" || address == null){
            addressFlag = false;
        }
        //姓名、身份证号码、年龄、地址都不为空
        if (nameFlag && idCardFlag && ageFlag && addressFlag) {
            return true;
        }else {
            return false;
        }
    }
    public boolean compareStudents(Student student1, Student student2){
        boolean nameFlag = true;
        boolean idCardFlag = true;
        boolean ageFlag = true;
        boolean addressFlag = true;
        boolean statusFlag = true;
        //判断姓名是否相同
        if (student1.getName().equals(student2.getName())){
            nameFlag = false;
        }
        //判断身份证号码是否相同
        if (student1.getIdCard().equals(student2.getIdCard())){
            idCardFlag = false;
        }
        //判断年龄是否相同
        if (student1.getAge().equals(student2.getAge())){
            ageFlag = false;
        }
        //判断地址是否相同
        if (student1.getAddress().equals(student2.getAddress())){
            addressFlag = false;
        }
        //判断数据是否一致，不一致就修改
        if (student1.getId().equals(student2.getId()) &&(nameFlag||idCardFlag||ageFlag||addressFlag)){
            return true;
        }else {
            return false;
        }
    }
}
